### CREATE ANALYTIC FILE

# A) Set global parameters

# Max number of current projects:

L <- 3

# Min number of prior projects:

K <- 2

# Indicator for use of sample:

samp <- FALSE

# B) Load data and create basic variables

source("setup.R")

# C) Constructed functions and variables

# Production function:

source("prodfn.R")

# Project-level variables:

source("proj_vars_c2.R")

# Draw sample of researchers:

if (samp) source("sample.R")

# Individual-level variables:

source("indiv_vars_c2.R")

# D) Network types

# Table of types and their frequencies:

source("types.R")

# Type-level variables:

source("type_vars_c2.R")

source("add_proj_c2.R")

# Save:

if (samp) save.image("analytic_c2_samp.RData") else save.image("analytic_c2_pop.RData")

# E) Collect rare types into residual categories

source("resid_cats_c2.R")

# F) Revise type variables

source("type_vars_c2.R")

source("add_proj_c2.R")

# V-Cov for confidence region:

if (samp) source("confidence.R")
	
# Save:

if (samp) save.image("analytic_c2_samp_res.RData") else save.image("analytic_c2_pop_res.RData")



### EXPORT TO MATLAB

# Make useful lists of type indices:

source("indices.R")

# Export to Matlab:

library(R.matlab)

if (samp) {

writeMat("analytic_c2_samp.mat", N=N_auth_exp, N_Z=N_Z,
	types=types, N_types=N_types, obs_shares=obs_shares, 
	feasible=feasible_idx, isolated=isolated_idx, residual1=residual1_idx, residual2=residual2_idx,
	Xp_t=Xp_t, Y_t=Y_t, N_t=N_t, dif_t=dif_t, l_t=l_t,
	Add_1auth=Add_1auth, Add_2auth=Add_2auth,
	C=C_full, hyp_lim=hyp_lim
)

} else {

writeMat("analytic_c2_pop.mat", N=N_auth_exp, N_Z=N_Z,
	types=types, N_types=N_types, obs_shares=obs_shares, 
	feasible=feasible_idx, isolated=isolated_idx, residual1=residual1_idx, residual2=residual2_idx,
	Xp_t=Xp_t, Y_t=Y_t, N_t=N_t, dif_t=dif_t, l_t=l_t,
	Add_1auth=Add_1auth, Add_2auth=Add_2auth
)

}
